package com.hckjsec.common.ueditor;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;

import com.hckjsec.common.config.FileInfoView;
import com.hckjsec.common.config.JeeThinkConfig;
import com.hckjsec.common.ueditor.domain.CloudApiConfig;
import com.hckjsec.common.ueditor.domain.UploadImgConfig;
import com.hckjsec.common.utils.file.FileUploadUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Optional;

/**
 * OSS工具类
 */
public final class OssUtils {
    private static final Logger log = LoggerFactory.getLogger(OssUtils.class);

    private OssUtils() {}

    /**
     * 默认格式化方式
     */
    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMM/dd/HHmmssSSS", Locale.CHINESE);

    public static final ClientConfiguration DEFAULT_CLIENT_CONFIGURATION = new ClientConfiguration();

    /**
     * 进行图片上传
     */
    public static BaseState uploadImg(CloudApiConfig cloudApiConfig, UploadImgConfig uploadImgConfig,String accessUrlPrefix, MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return new BaseState(false, 7);
        }
        String contentType = file.getContentType();
        if (!contentType.matches("^image/(?:png|jpg|jpeg|gif|bmp)$")) {// 文件格式不匹配
            return new BaseState(false, 8);
        }
        return upload(cloudApiConfig, uploadImgConfig,accessUrlPrefix, file);
    }

    /**
     * 进行文件上传
     * 返回值为BaseState是为了让前端ueditor能够识别
     * 同时因为BaseState有返回上传后的url，能够满足业务需求
     */
    public static BaseState upload(CloudApiConfig cloudApiConfig, UploadImgConfig uploadImgConfig,String accessUrlPrefix, MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return new BaseState(false, 7);
        }
        String fileName = file.getOriginalFilename();
        if (!validSize(file.getSize(), uploadImgConfig.getMaxSize())) {
            return new BaseState(false, 1);
        }
//        OSSClient ossClient = null;
        try {
            String suffix = "." + FilenameUtils.getExtension(fileName);
//
//            // 工程中可以有多个OSSClient，也可以只有一个OSSClient；OSSClient可以并发使用；OSS支持https，当您的安全需求更高时，可以使用https；OSSClient.shutdown之后不能再使用。
//            ossClient = new OSSClient(cloudApiConfig.getOssEndpoint(), cloudApiConfig.getAccessKeyId(),
//                    cloudApiConfig.getAccessKeySecret(), DEFAULT_CLIENT_CONFIGURATION);
//            String dt = new StringBuilder()
//                    .append(LocalDateTime.now().format(DATE_TIME_FORMATTER))
//                    .append(RandomStringUtils.randomAlphabetic(6))
//                    .append(suffix)
//                    .toString();
//            ossClient.putObject(cloudApiConfig.getOssBucketName(), dt, file.getInputStream());
//            // 需要注意，这里的uploadImgConfig.getAccessUrlPrefix()
//            // 虽然是上传到OSS，但是很多情况下并不会直接通过OSS访问上传的文件
//            // 因为可能涉及跨域等其他问题，所以采用配置访问前缀拼接上oss路径的方式来避免此问题
//            String accessUrl = new StringBuilder()
//                    .append(uploadImgConfig.getAccessUrlPrefix())
//                    .append("/").append(dt).toString();
            String domainName = accessUrlPrefix;
            // 上传文件路径
            String filePath = JeeThinkConfig.getUploadPath();
            // 上传并返回新文件名称
            FileInfoView fileInfoView = FileUploadUtils.hcUpload(filePath, file);
            BaseState storageState = new BaseState(true);
            storageState.putInfo("size", file.getSize());
            storageState.putInfo("title", file.getName());
            storageState.putInfo("url", domainName+fileInfoView.getPathFileName());
            storageState.putInfo("type", suffix);
            storageState.putInfo("original", "");
            return storageState;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
//            Optional.ofNullable(ossClient).ifPresent(OSSClient::shutdown);
        }
        return new BaseState(false, 6);
    }

    /**
     * 校验文件大小
     * @param dataLength dataLength
     * @param maxSize maxSize
     * @return boolean
     */
    public static boolean validSize(long dataLength, long maxSize) {
        return maxSize == -1 || dataLength <= maxSize;
    }
}

